package xian.woniuxy.d_cache;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Arrays;
import java.util.List;

/**
 * @author gao
 * @time 2021/12/24 09:26:28
 */
public class MyRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        Object pricipal = principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo sa = new SimpleAuthorizationInfo();
        if ("foo".equals(pricipal)) {
            sa.addStringPermission("user:save");
            sa.addStringPermission("user:delete");
        }
        if ("bar".equals(pricipal)) {
            sa.addStringPermission("user:update");
            sa.addStringPermission("user:find");
        }
        return sa;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");
        Object principal = authenticationToken.getPrincipal();

        List<String> accountList = Arrays.asList("foo", "bar");
        if (!accountList.contains(principal)) {
            return null;
        }

        // select password from users where username = ?
        String password = null;
        if ("foo".equals(principal)) {
            password = "123";
        }
        if ("bar".equals(principal)) {
            password = "456";
        }

        return new SimpleAuthenticationInfo(principal, password, "myRealm");
    }
}
